package com.siyue.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.siyue.entity.User;
import com.siyue.entity.UserStatus;
import com.siyue.mapper.UserMapper;
import com.siyue.util.JWTUtil;
import com.siyue.util.MD5Utils;
import com.siyue.util.RedisUtil;
import com.siyue.util.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private MD5Utils md5Utils;

    @Autowired
    private JWTUtil jwtUtil;


    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    public RestResponse userLogin(String username, String password, String code, HttpServletRequest request) {
        RestResponse result = new RestResponse();
        JSONObject token = new JSONObject();

        String sessionId = request.getSession().getId();
        String codeStr = (String) redisUtil.get(sessionId);

        User user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));

        String userInfo = (String) redisUtil.get(username);//用户登录redis中的信息（错误次数、是否锁定）

        int frequency = 0;

        if (null != userInfo && !"".equals(userInfo)) {
            JSONObject json = JSON.parseObject(userInfo);
            frequency = json.getInteger("frequency");
            System.out.println(json.getString("lockStatus").equals("1"));
            if (json.getString("lockStatus").equals("1")) {
                result.setStatus("error");
                result.setMessage("当前用户锁定,请5分钟后重试");
                return result;
            }
        }
        System.out.println(code);
        if (code.equalsIgnoreCase(codeStr) && null != user && user.getPassword().equals(password)) {
            redisUtil.del(username);
            redisUtil.del(sessionId);
            String tokenInfo = jwtUtil.sign(username, password);
            redisUtil.setex("PREFIX_USER_TOKEN_" + tokenInfo, tokenInfo, 30 * 60);
            token.put("token", tokenInfo);
            token.put("username", username);
            token.put("id", user.getId());
            token.put("roleId", user.getRoleId());
            result.setStatus("success");
            result.setData(token);
        } else {
            redisUtil.del(sessionId);
            UserStatus userStatus = new UserStatus();
            if (null != userInfo && !"".equals(userInfo)) {
                userStatus.setFrequency(frequency + 1);
                if (userStatus.getFrequency() >= 3) {
                    userStatus.setFrequency(0);
                    userStatus.setLockStatus("1");
                    userStatus.setLockTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                } else {
                    userStatus.setLockStatus("0");
                }
            } else {
                userStatus.setFrequency(1);
                userStatus.setLockStatus("0");
            }
            redisUtil.setex(username, JSONObject.toJSONString(userStatus), 300);
            if (!code.equalsIgnoreCase(codeStr)) {
                result.setStatus("error");
                result.setMessage("验证码输入错误");
            } else {
                result.setStatus("error");
                result.setMessage("用户名或密码输入错误");
            }
        }
        return result;
    }

    /**
     * 获取验证码
     *
     * @param result
     * @param request
     */
    public void getCode(RestResponse result, HttpServletRequest request) {
        String sessionId = request.getSession().getId();
        Random randObj = new Random();
        String code = Integer.toString(1000 + randObj.nextInt(9000));
        redisUtil.set(sessionId, code);
        result.setMessage("success");
        result.setData(code);
    }

}
